<template>
	<view class="field-checkbox field-form-item">
		<u-form-item :label="label" :required="required" :prop="prop">
			<u-checkbox-group
				style="margin: 0;"
				:value="checkVal"
				:disabled="disabled"
				:size="iconSize"
				:active-color="activeColor"
				:wrap="direction != 'horizontal'"
			>
				<u-checkbox
					v-for="item in dataList"
					:key="item[props.value]"
					:name="item[props.value]"
					:value="checkVal.indexOf(item[props.value]) !== -1"
					@input="(val) => onCheckboxChange(item, val)"
				>
					{{ item[props.label] }}
				</u-checkbox>
			</u-checkbox-group>
		</u-form-item>
	</view>
</template>

<script>
	import style from 'uni.scss';
	import { validateWidget } from '@/utils/validate.js';

	export default {
		name: 'fieldCheckbox',
		options: {
			styleIsolation: 'shared', // 解除样式隔离
		},
		props: {
			label: {
				type: String
			},
			value: {
				type: [Array]
			},
			prop: {
				type: String
			},
			iconSize: {
				type: [String, Number],
				default: 28
			},
			direction: {
				type: String,
				default: 'horizontal'
			},
			activeColor: {
				type: String,
				default: style.primary_color
			},
			required: {
				type: Boolean,
				default: false
			},
			disabled: {
				type: Boolean,
				default: false
			},
			dataList: {
				type: Array,
				default: () => []
			},
			props: {
				type: Object,
				default: () => {
					return {
						value: 'id',
						label: 'name'
					}
				}
			}
		},
		data() {
			return {
				dirty: false,
				errorMessage: ''
			}
		},
		methods: {
			onCheckboxChange(data, val) {
				let arr = this.checkVal;
				if (val) {
					arr.push(data[this.props.value]);
				} else {
					arr.splice(arr.indexOf(data[this.props.value]), 1);
				}
				console.log(arr);
				this.$emit('input', arr);
				this.$emit('change', arr);
			},
			validateWidget() {
				return new Promise((resolve, reject) => {
					validateWidget(this.rules, this.value).then(res => {
						this.errorMessage = '';
						resolve();
					}).catch(e => {
						this.errorMessage = e;
						resolve(e)
					});
				});
			}
		},
		computed: {
			checkVal() {
				if (Array.isArray(this.value)) return this.value;
				return [];
			}
		}
	}
</script>

<style scoped>
	.van-vertical-item+.van-vertical-item {
		margin-top: 16rpx;
	}

	.van-field-radio ::v-deep .van-radio--horizontal {
		margin-right: 0px;
	}

	.van-field-radio ::v-deep .van-radio--horizontal+.van-radio--horizontal {
		margin-left: 32rpx;
	}
</style>
<style>
</style>